package org.tigris.atlas.xml.schema.mda.generator;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.tigris.atlas.mda.metadata.element.Composite;
import org.tigris.atlas.mda.metadata.element.Entity;
import org.tigris.atlas.mda.metadata.element.Enumeration;
import org.tigris.atlas.mda.metadata.element.Field;

public class SchemaContainer {

	private Map entityMap = new HashMap(10);
	private Map compositeMap = new HashMap(10);
	private Map enumerationMap = new HashMap(10);
	
	/**
	 * @return Returns the composites.
	 */
	public Collection getComposites() {
		return Collections.unmodifiableMap(compositeMap).values();
	}
	
	/**
	 * @return Returns the entitys.
	 */
	public Collection getEntities() {
		return Collections.unmodifiableMap(entityMap).values();
	}
	
	/**
	 * @return Returns the enumerations.
	 */
	public Collection getEnumerations() {
		return Collections.unmodifiableMap(enumerationMap).values();
	}
	
	public boolean containsEntity(String entityName) {
		return entityMap.containsKey(entityName);
	}
	
	public void addEntity(Entity entity) {
		if (entity != null) {
			if (!entityMap.containsKey(entity.getName())) {
				entityMap.put(entity.getName(), entity);
				getEnumerations(entity);
			}
		}
		
	}
	
	public boolean containsComposite(String compositeName) {
		return compositeMap.containsKey(compositeName);
	}
	
	public void addComposite(Composite composite) {
		if (composite != null) {		
			if (!compositeMap.containsKey(composite.getName())) {
				compositeMap.put(composite.getName(), composite);
				getEnumerations(composite);
			}
		}
		
	}
	
	private void getEnumerations(Entity entity) {
		Map fieldMap = entity.getFields();
		getEnumerationFromFields(fieldMap.values());
	}
	
	private void getEnumerations(Composite composite) {
		Collection fields = composite.getFields();
		getEnumerationFromFields(fields);
	}
	
	private void getEnumerationFromFields(Collection fields) {
		if ((fields != null) &&  (fields.size() > 0)) {
			Field field;
			Enumeration enumeration;
			Iterator i = fields.iterator();
			while (i.hasNext()) {
				field = (Field)i.next();		
				enumeration = field.getEnumeration();			
				if (enumeration != null) {
					addEnumeration(enumeration);
				}
			}
			
		}
	}
	
	public boolean containsEnumeration(String enumerationName) {
		return enumerationMap.containsKey(enumerationName);
	}
	
	public void addEnumeration(Enumeration enumeration) {
		if (enumeration != null) {
			if (!enumerationMap.containsKey(enumeration.getName())) {
				enumerationMap.put(enumeration.getName(), enumeration);
			}
		}
		
	}	
	
}
